<script setup>
import { ref, reactive } from 'vue'
import { userApi } from '../api/user'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const userDetail = ref(null)
const loading = ref(false)
const isEditing = ref(false)

const editForm = reactive({
  name: '',
  email: '',
  gender: '',
  phone: ''
})

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

const showDialog = async () => {
  dialogVisible.value = true
  isEditing.value = false
  await loadUserDetail()
}

const loadUserDetail = async () => {
  try {
    loading.value = true
    console.log('开始获取用户信息')
    const res = await userApi.getUserDetail()
    console.log('API响应数据:', res)
    
    // 检查响应数据
    if (!res) {
      throw new Error('API响应为空')
    }

    // 如果响应中包含data字段，使用data中的数据
    const userData = res.data || res
    console.log('处理后的用户数据:', userData)

    // 设置用户详情数据
    userDetail.value = {
      id: userData.id,
      username: userData.username,
      name: userData.name,
      email: userData.email,
      gender: userData.gender,
      phone: userData.phone,
      role: userData.role,
      is_superuser: userData.is_superuser,
      is_staff: userData.is_staff,
      login_count: userData.login_count,
      last_login: userData.last_login,
      created_at: userData.created_at,
      updated_at: userData.updated_at,
      ip_address: userData.ip_address
    }
    console.log('设置用户详情数据:', userDetail.value)
    
    // 初始化编辑表单
    Object.assign(editForm, {
      name: userData.name,
      email: userData.email,
      gender: userData.gender,
      phone: userData.phone || ''
    })
    console.log('编辑表单数据:', editForm)
  } catch (error) {
    console.error('获取用户信息出错:', error)
    ElMessage.error('获取用户信息失败')
    userDetail.value = null
  } finally {
    loading.value = false
  }
}

const handleEdit = () => {
  isEditing.value = true
}

const handleCancel = () => {
  isEditing.value = false
  // 重置表单，添加空值检查
  if (userDetail.value) {
    Object.assign(editForm, {
      name: userDetail.value.name || '',
      email: userDetail.value.email || '',
      gender: userDetail.value.gender === '男' ? 'M' : 'F',
      phone: userDetail.value.phone || ''
    })
  } else {
    // 如果 userDetail 为空，重置为默认值
    Object.assign(editForm, {
      name: '',
      email: '',
      gender: 'M',
      phone: ''
    })
  }
}

const handleSave = async () => {
  try {
    loading.value = true
    await userApi.updateUser(userDetail.value.id, editForm)
    ElMessage.success('更新成功')
    isEditing.value = false
    await loadUserDetail() // 重新加载用户信息
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('更新失败')
    }
  } finally {
    loading.value = false
  }
}

defineExpose({
  showDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEditing ? '编辑个人信息' : '个人信息'"
    width="500px"
    destroy-on-close
  >
    <el-skeleton v-if="loading" :rows="6" animated />
    
    <el-form
      v-else-if="userDetail"
      ref="formRef"
      :model="editForm"
      :rules="rules"
      label-width="100px"
      :disabled="!isEditing"
    >
      <el-form-item label="用户名">
        <span>{{ userDetail.username }}</span>
      </el-form-item>
      
      <el-form-item label="姓名" prop="name">
        <template v-if="isEditing">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </template>
        <template v-else>
          <span>{{ userDetail.name }}</span>
        </template>
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <template v-if="isEditing">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </template>
        <template v-else>
          <span>{{ userDetail.email }}</span>
        </template>
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <template v-if="isEditing">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="M">男</el-radio>
            <el-radio label="F">女</el-radio>
          </el-radio-group>
        </template>
        <template v-else>
          <span>{{ userDetail.gender }}</span>
        </template>
      </el-form-item>
      
      <el-form-item label="手机号">
        <template v-if="isEditing">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </template>
        <template v-else>
          <span>{{ userDetail.phone }}</span>
        </template>
      </el-form-item>
      
      <el-form-item label="角色">
        <el-tag :type="userDetail.is_superuser ? 'danger' : userDetail.is_staff ? 'warning' : 'info'">
          {{ userDetail.role }}
        </el-tag>
      </el-form-item>
      
      <el-form-item label="登录次数">
        <span>{{ userDetail.login_count }}</span>
      </el-form-item>
      
      <el-form-item label="最后登录">
        <span>{{ userDetail.last_login }}</span>
      </el-form-item>
      
      <el-form-item label="创建时间">
        <span>{{ userDetail.created_at }}</span>
      </el-form-item>
      
      <el-form-item label="更新时间">
        <span>{{ userDetail.updated_at }}</span>
      </el-form-item>
      
      <el-form-item label="IP地址">
        <span>{{ userDetail.ip_address }}</span>
      </el-form-item>
    </el-form>
    
    <el-empty v-else description="获取用户信息失败" />
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <template v-if="userDetail && !isEditing">
          <el-button type="primary" @click="handleEdit">
            编辑
          </el-button>
        </template>
        <template v-if="isEditing">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="loading">
            保存
          </el-button>
        </template>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-form {
  padding: 0 16px;
}

:deep(.el-form-item__content) {
  justify-content: flex-start;
}

:deep(.el-dialog__body) {
  padding: 20px 0;
}
</style> 